package com.freesun.shop.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freesun.shop.entity.IndexImg;
import com.freesun.shop.entity.Prod;
import com.freesun.shop.mapper.IndexImgMapper;
import com.freesun.shop.service.IndexImgService;
import com.freesun.shop.service.ProdService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 主页轮播图 服务实现类
 * </p>
 *
 * @author zf
 * @since 2019-11-13
 */
@Service
@CacheConfig(cacheNames = "com.freesun.shop.entity.IndexImg")
public class IndexImgServiceImpl extends ServiceImpl<IndexImgMapper, IndexImg> implements IndexImgService {

    private static Logger logger = LoggerFactory.getLogger(IndexImgServiceImpl.class);
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Reference(check = false)
    private ProdService prodService;
    @Override
    public IPage<IndexImg> findByPage(IndexImg indexImg, Page<IndexImg> page) {
        logger.info("轮播图分页查询开始,当前页:{},每页显示大小:{}",page.getCurrent(),page.getSize());
        IPage<IndexImg> iPage = this.baseMapper.selectPage(page, new LambdaQueryWrapper<IndexImg>()
                .eq(indexImg.getStatus() != null, IndexImg::getStatus, indexImg.getStatus()));
        return iPage;
    }

    @Override
    @Cacheable(key = "#id")
    public IndexImg getById(Serializable id) {
        logger.info("单个轮播图查询id:{}",id);
        IndexImg indexImg = super.getById(id);
        if (indexImg.getRelation() != null) {
            Prod prod = prodService.getById(indexImg.getRelation());
            indexImg.setPic(prod.getPic());
            indexImg.setProdName(prod.getProdName());
        }

        return indexImg;
    }

    /**
     * 批量清空
     * @param idList
     * @return
     */
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        Assert.notNull(idList,"批量删除时,id集合不能为空");
        logger.info("批量删除轮播图：{}",idList);
        List<String> deleteKeys = new ArrayList<>(idList.size());
        idList.forEach((idLong)->{
            deleteKeys.add("com.freesun.shop.entity.IndexImg::"+idLong);
        });
        redisTemplate.delete(deleteKeys);
        boolean flag = super.removeByIds(idList);
        return flag;
    }

    @Override
    @CacheEvict(key = "#id")
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    @Override
    public boolean save(IndexImg entity) {
        Assert.notNull(entity,"新增的数据不能为Null");
        check(entity);
        entity.setUploadTime(LocalDateTime.now());
        return super.save(entity);
    }

    private void check(IndexImg entity) {
        if(entity.getImgUrl()==null||entity.getType()==null){
            throw new RuntimeException("数据格式错误");
        }
        switch (entity.getType()) {
            case -1:
                if (entity.getLink() == null) {
                    throw new RuntimeException("轮播图必须有连接地址");
                }
                break;
            case 0:
                if (entity.getRelation() == null) {
                    throw new RuntimeException("轮播关联的商品不能为空");
                }
                break;
             default:
                 throw new RuntimeException("不合法的商品类型");

        }
    }

    @Override
    @CacheEvict(key = "#entity.imgId")
    /**
     * 也可以使用@Caching 自己定义多种缓存规则
     */
   /* @Caching(
            evict = {
                    @CacheEvict(key = "#entity.imgId"),
                    @CacheEvict(key = INDEX_IMG_DATA)
            }
    )*/
    public boolean updateById(IndexImg entity) {
        Assert.notNull(entity,"修改的数据不能为Null");
        Assert.notNull(entity.getImgId(),"修改的数据ID不能为Null");
        check(entity);
        IndexImg indexImg = getById(entity.getImgId());
        if(indexImg==null){
            throw new RuntimeException("要修改的数据不存在");
        }
        return super.updateById(entity);
    }

    /**
     * 加载微信的首页轮播图
     * @return
     */
    private static final String INDEX_IMG_DATA="'index-all-data'";
    @Override
    @Cacheable(key = INDEX_IMG_DATA)
    public List<IndexImg> getIndexImgs() {
        List<IndexImg> indexImgs = this.baseMapper.selectList(new LambdaQueryWrapper<IndexImg>()
                .eq(IndexImg::getStatus, 1)
                .orderByAsc(IndexImg::getSeq));
        return indexImgs;
    }
}
